package com.sinacom.ibuilding.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.StringCharacterIterator;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.sinacom.ibuilding.beans.News;



public class Helper {
	
	private static	Calendar cal1=Calendar.getInstance();
	
	public static boolean  isEmpty(String str){
		
		return str==null || str.equals("");
	}
	
	public static String getCurrrentTime(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(new Date());
	}
	
	
	public static int getYear(Date date){
		cal1.setTime(date);
		return cal1.get(Calendar.YEAR); 
	}
	public static int getMonth(Date date){
		cal1.setTime(date);
		return cal1.get(Calendar.MONTH)+1; 
	}
	public static int getDay(Date date){
		cal1.setTime(date);
		return cal1.get(Calendar.DATE); 
	}
	public static int getHour(Date date){
		cal1.setTime(date);
		return cal1.get(Calendar.HOUR_OF_DAY); 
	}
	public static int getMinute(Date date){
		cal1.setTime(date);
		return cal1.get(Calendar.MINUTE); 
	}
	public  static int getMonth(String time) {
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		Date date = null;
		try {
			date = format1.parse( time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		cal1.setTime(date);
		return cal1.get(Calendar.MONTH); 
	}
	
	public  static int getDay(String time) {
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		Date date = null;
		try {
			date = format1.parse( time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		cal1.setTime(date);
		return cal1.get(Calendar.DATE); 
	}
	
	public  static int getDayOfWeek(String time) {
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		Date date = null;
		try {
			date = format1.parse( time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		cal1.setTime(date);
		return cal1.get(Calendar.DAY_OF_WEEK); 
	}
	
	public  static int getDayOfMonth(String time) {
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		Date date = null;
		try {
			date = format1.parse( time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		cal1.setTime(date);
		return cal1.get(Calendar.DAY_OF_MONTH); 
	}
	
	public  static int getHour(String time) {
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		Date date = null;
		try {
			date = format1.parse( time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		cal1.setTime(date);
		return cal1.get(Calendar.HOUR_OF_DAY); 
	}
	
	public  static int getMinute(String time) {
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		Date date = null;
		try {
			date = format1.parse( time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		cal1.setTime(date);
		return cal1.get(Calendar.MINUTE); 
	}
	
	public  static String getFormateDate(String time,String formate) {
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		DateFormat format2 = new SimpleDateFormat(formate); 
		Date date = null;
		String str = null;
		try {
			date = format1.parse( time);
			str = format2.format(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return str;
	}
	
	public static Date getDateByStr(String time){
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		Date date = null;
		try {
			date = format1.parse(time);
		} catch (ParseException e) {
		}
		return date;
	}
	
	public static Date parseDate(String time,String formate){
        DateFormat format1 = new SimpleDateFormat(formate); 
        Date date = null;
        try {
            date = format1.parse(time);
        } catch (ParseException e) {
        }
        return date;
    }
	
	public static String getFormatDate(Date date){
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format1.format(date);
	}
	
	public static long dateWeek(Date date1, Date date2) {
		long time1 = date1.getTime();
		long time2 = date2.getTime();
		long week = (time1-time2)/(1000*3600*24*7);
		return week;
	}
	
	public static long dateDay(Date date1, Date date2) {
		long time1 = date1.getTime();
		long time2 = date2.getTime();
		long day = (time1-time2)/(1000*3600*24);
		return day;
	}
	public static void newList(List list){
		if(list != null && list.size() > 0){
			Date now = new Date();
			boolean retain = false;
			for (int j = 0; j < list.size(); j++) {
				News news = (News) list.get(j);
				Date createTime = news.getCreateDate();
				long day = Helper.dateDay(now, createTime);
				if(day < 1){
					retain = true;
					break;
				}
			}
			for (int j = 0; j < list.size(); j++) {
				News news = (News) list.get(j);
				if(retain){
		    		long day = Helper.dateDay(now,news.getCreateDate());
		    		if(day < 1){
		    			news.setIsNew(Boolean.TRUE);
		    		}
				}else{
		    		long week = Helper.dateWeek(now,news.getCreateDate());
		    		if(week < 1){
		    			news.setIsNew(Boolean.TRUE);
		    		}
				}
			}
		}
		
	}
	public static boolean  sendShortMsg(String mobile,String content){
		return sendShortMsg(mobile, content, null);
	}
	public static String getNumTag(){
		return getNumTag(253, 260);
	}
	
	public static String getNumTag(int min,int max){
		return String.valueOf(Math.round(Math.random()*(max-min)+min));
	}
	
	public static boolean  sendShortMsg(String mobile,String content,String numTag){
		if(StringUtils.isEmpty(numTag)){
			numTag = getNumTag();
		}
        try{
            URL url = new URL("http://218.78.214.91:7001/corsms/Sendsms?oriadd="+numTag+"&taradd="+mobile+"&content="+URLEncoder.encode(content, "GBK"));
//          URL url = new URL("http://www.baidu.com/");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer();
            while ((lines = reader.readLine()) != null) {
                System.out.println(lines);
                if(!StringUtils.isEmpty(lines)){
                    sb.append(lines);
                }
            }
            if("OKOKOKOK".equals(sb.toString())){
                return true;
            }
            reader.close();
            // 断开连接
            connection.disconnect();
        }catch(IOException e){
            e.printStackTrace();
            return false;
        }
        
        return false;
    }
	
	
	/*public static String getRmember(String rmember){
		if(StringUtils.isEmpty(rmember)) return null;
		 String rms[] = rmember.split(";");
         
         StringBuffer sb = new StringBuffer();
         
         for (int i = 0; i < rms.length; i++) {
         	String rmdet = rms[i];
 			String username = null;
 			if(rmdet.startsWith("(") && rmdet.endsWith(")")){
 				String[] rmdets = rmdet.substring(1,rmdet.length()-1).split(",");
 				username = rmdets[2];
 				sb.append(username);
 				sb.append(";");
 			}
         	
         }
         return sb.toString();
	}*/
	
	public static String getRmember(String rmember){
		if(StringUtils.isEmpty(rmember)) return null;
		 String rms[] = rmember.split(";");
         
         StringBuffer sb = new StringBuffer();
         
         for (int i = 0; i < rms.length; i++) {
         	String rmdet = rms[i];
 			String username = null;
			String[] rmdets = rmdet.split("#");
			username = rmdets[2];
			boolean hasName = false;
			for (int j = 0; j < rms.length; j++) {
				String rmdet2 = rms[j];
				String[] rmdets2 = rmdet2.split("#"); 
				if(!(rmdets[0].equals(rmdets2[0]) && rmdets[1].equals(rmdets2[1])) && rmdets[2].equals(rmdets2[2])){
					hasName = true; 
				}
			}
			if(hasName){
				sb.append(username);
				sb.append("("+rmdets[0]+")");
				sb.append(";");
			}else{
				sb.append(username);
				sb.append(";");
			}
			
			
         }
         return sb.toString();
	}
	

	public static boolean testAcceptMsg(){
		try{
           // URL url = new URL("http://218.78.214.23:7001/huangpu/acceptmsg!index.do?FromMobile=13564369099&Content="+URLEncoder.encode("代码测试短信乱码", "GBK")+"&NumTag=260");
            URL url = new URL("http://localhost:7001/huangpu/acceptmsg!index.do?FromMobile=13564369099&Content="+URLEncoder.encode("代码测试短信乱码", "GBK")+"&NumTag=259");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer();
            while ((lines = reader.readLine()) != null) {
                System.out.println(lines);
                if(!StringUtils.isEmpty(lines)){
                    sb.append(lines);
                }
            }
            if("Receive".equals(sb.toString())){
                return true;
            }
            reader.close();
            // 断开连接
            connection.disconnect();
        }catch(IOException e){
            e.printStackTrace();
            return false;
        }
		return false;
	}
	
	public static void main(String[] args) throws UnsupportedEncodingException {
//		System.out.println(getNumTag(260, 251));
		testAcceptMsg();
	//	System.out.println(URLEncoder.encode("这是一个测试", "GBK"));
	//	System.out.println(URLDecoder.decode("%D5%E2%CA%C7%D2%BB%B8%F6%B2%E2%CA%D4", "gbk"));
	//	System.out.println(new String("%D5%E2%CA%C7%D2%BB%B8%F6%B2%E2%CA%D4".getBytes("ISO-8859-1"),"GBK"));
	}

	public static String nl2br(String text) {
        if (text == null || text.length() == 0) {
            return text;
        }
        StringBuffer sb = new StringBuffer(text.length() * 2);
        StringCharacterIterator iterator = new StringCharacterIterator(text);
        char character = iterator.current();
        while (character != StringCharacterIterator.DONE) {
            switch (character) {
                case '\r':
                    sb.append("<br/>");
                    sb.append(character);
                    character = iterator.next();
                    if (character == '\n') {
                        character = iterator.next();
                    }
                    break;
                case '\n':
                    sb.append("<br/>");
                    sb.append(character);
                    character = iterator.next();
                    if (character == '\r') {
                        sb.append(character);
                        character = iterator.next();
                    }
                    break;
                default:
                    sb.append(character);
                    character = iterator.next();
                    break;
            }
        }
        return sb.toString();
    }
	

}
